import com.bulenkov.darcula.DarculaLaf;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * Created by LLAP on 2017/12/5.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class Board extends JFrame {
    private JPanel main;
    private JLabel[] labels;
    private String multiCastIP = "224.116.8.2";
    private int port = 817;
    private InetAddress group;
    private MulticastSocket msocket;
    private DatagramPacket pack;
    byte[] buf;

    public Board() {
        super();
        try {
            UIManager.setLookAndFeel(new DarculaLaf());
        } catch (Exception e) {
            try {
                UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
            }
            catch (Exception ex) {
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                }
                catch (Exception exc) {
                    System.out.println("Substance Raven Graphite failed to initialize");
                }
            }
        }
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        this.setSize(400, 200);
        main = new JPanel(new GridLayout(4, 1, 15, 15));
        main.setBorder(new EmptyBorder(10, 10, 10, 10));
        this.setContentPane(main);
        labels = new JLabel[4];
        for (int i = 0; i < 4; i++) {
            labels[i] = new JLabel("");
            labels[i].setFont(new java.awt.Font("Microsoft Yahei UI", 0, 20));
            main.add(labels[i]);
        }
        try {
            msocket = new MulticastSocket(port);
            group = InetAddress.getByName(multiCastIP);
            msocket.joinGroup(group);
            buf = new byte[512];
            pack = new DatagramPacket(buf, buf.length, group, port);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        new Thread(() -> {
//            System.out.println("Getting queue information from server...");
            while(true) {
                try {
                    msocket.receive(pack);
                    String message = new String(pack.getData(), 0, pack.getLength());
//                    System.out.println("Received: " + message);
                    for (int i = 3; i > 0; i--) {
//                        System.out.println(labels[i - 1].getText());
                        labels[i].setText(labels[i - 1].getText());
                    }
                    labels[0].setText(message);
//                    System.out.println("Redraw");
                    this.main.updateUI();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static void main(String[] args) {
        new Board().setVisible(true);
    }
}
